<?php
/**
 * ws 优化 基础类库
 */
class Ws{
    CONST HOST = '0.0.0.0';
    CONST PORT = 6065;
    public $ws = null;
    public function __construct()
    {
        $this->ws = new \Swoole\WebSocket\Server('0.0.0.0',6065);
        //链接事件
        $this->ws->on("open",[$this,"onOpen"]);
        $this->ws->set(
            [
                'worker_num'=>4,
                'task_worker_num'=>4
            ]
        );
        //消息事件
        $this->ws->on("message",[$this,"onMessage"]);
        //task事件
        $this->ws->on("task",[$this,"onTask"]);
        $this->ws->on("finish",[$this,"onFinish"]);

        //关闭事件
        $this->ws->on('close',[$this,'onClose']);
        //启动
        $this->ws->start();
    }

    /**
     *监听ws链接事件
     * @param $ws
     * @param $request
     */
    public function onOpen($ws,$request)
    {
         print_r($request->fd);
         if($request->fd == 1)
         {
             //每2秒中执行一次
             swoole_timer_tick(2000,function($timer_id)
             {
                 echo "2s:timeId:{$timer_id}\n";
             });
         }
    }

    /**
     *监听ws消息事件
     * @param $ws
     * @param $frame
     */
    public function onMessage($ws,$frame)
    {
        echo "server_push_message:{$frame->data}\n";
        //收到客户端消息后 todo 10s
        $data = [
            'task'=>1,
            'fd'=>$frame->fd,
        ];
//        $ws->task($data);
        swoole_timer_after(5000,function () use ($ws,$frame)
        {
            echo "5s-after\n";
            $ws->push($frame->fd,"server-time-after:冯勤测试after测试");
        });
        $ws->push($frame->fd,"server-push:".date('Y-m-d H:i:s'));
    }

    /**
     * @param $serv
     * @param $task_id
     * @param $reactor_id
     * @param $data
     * @return string
     */
    public function onTask($ws, $task_id, $reactor_id, $data)
    {
//        print_r($serv);
        print_r($data);
//        $fd = $data['fd'];
        //耗时的场景
        sleep(10);
        $ws->push($data['fd'],"server-push:".date('Y-m-d H:i:s')." 10秒后   哈哈哈哈");
        return "on task finish";//告诉worker
    }

    /**
     * @param $serv
     * @param $task_id
     * @param $data
     */
    public function onFinish($ws,$task_id,$data)
    {
        echo "task_id:{$task_id}\n";
        echo "finish-success:{$data}\n";
    }
    /**
     * 关闭连接
     * @param $ws
     * @param $fd
     */
    public function onClose($ws,$fd)
    {
        echo "client_id:{$fd}\n";
    }

}
$obj = new Ws();